import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class BlockingQueueThreadComminication {
	static class DataWrap{
		int data;
	}
	
	static class ThreadA extends Thread{
		private BlockingQueue<DataWrap> blockingQueue;
		
		public ThreadA(BlockingQueue<DataWrap> blockingQueue, String name) {
			super(name);
			this.blockingQueue = blockingQueue;
		}
		
		@Override
		public void run() {
			for (int i = 0; i < 100; i++) {
				try {
					DataWrap dataWrap = blockingQueue.take();
					
					dataWrap.data++;
					System.out.println(getName() + " " + dataWrap.data);
					sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	static class ThreadB extends Thread{
		private BlockingQueue<DataWrap> blockingQueue;
		private DataWrap dataWrap;
		
		public ThreadB(BlockingQueue<DataWrap> blockingQueue, DataWrap dataWrap, String name) {
			super(name);
			this.blockingQueue = blockingQueue;
			this.dataWrap = dataWrap;
		}
		
		@Override
		public void run() {
			for (int i = 0; i < 100; i++) {
				try {
					dataWrap.data++;
					System.out.println(getName() + " " + dataWrap.data);
					blockingQueue.put(dataWrap);
					sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public static void main(String[] args) {
		///实现两个线程轮流对数据进行加一操作
		
		DataWrap dataWrap = new DataWrap();
		BlockingQueue<DataWrap> blockingQueue = new ArrayBlockingQueue<>(1);
		
		new ThreadA(blockingQueue, "Consumer").start();
		new ThreadB(blockingQueue, dataWrap, "Producer").start();
	}

}
